package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:uid:";

    /**
     * 添加商品到购物车
     * @param cart
     */
    public void addCart(Cart cart) {
        System.out.println("Service的当前用户："+ UserHolder.getUser().getUsername());
        // key
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 获取当前用户下的购物车
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 获取商品的id 和数量
        String skuId = cart.getSkuId().toString();
        Integer num = cart.getNum();
        // 判断当前商品是否已经存在redis
        Boolean bool = hashOps.hasKey(skuId);
        // 如果已经存在，修改数量
        if (bool != null && bool) {
            // 获取数据
            String jsonCart = hashOps.get(skuId);
            // 转对象
            cart = JsonUtils.toBean(jsonCart, Cart.class);
            // 修改数量
            cart.setNum(cart.getNum()+num);
        }
        // 存入redis中
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    /**
     * 查询购物车数据
     * @return
     */
    public List<Cart> queryCartList() {
        System.out.println("Service的当前用户："+ UserHolder.getUser().getUsername());
        // key
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 判断
        Boolean bool = redisTemplate.hasKey(key);
        if(bool == null || !bool){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 说明存在
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 判断数量
        Long size = hashOps.size();
        if(size == null || size < 1 ){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 如果存在
        List<String> carts = hashOps.values();
        /*List<Cart> cartList = new ArrayList<>();
        for (String c : carts) {
            Cart cart = JsonUtils.toBean(c, Cart.class);
            cartList.add(cart);
        }*/
        return carts.stream()
                .map(c -> JsonUtils.toBean(c, Cart.class))
                .collect(Collectors.toList());
    }
}
